/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

function initTD() {
  loadTopicList("td");
  
  //loadHeaderSub( lang );
  loadTypes( types ); // types defined in resources.js.jsp 
  
  //top needed!!
  top.document.title = "SEPIA: "+msg( lang, "msg_td" );
  
  loadMessages( lang );

  //after loading message
  if ( isMonolingual ) {
    $( "msg_question_src" ).style.display = "none";
    $( "questionSrc" ).style.display = "none";
    $( "msg_narrative_src" ).style.display = "none";
    $( "narrativeSrc" ).style.display = "none";
    
    $( "msg_question_trg" ).innerHTML  = $( "msg_question_trg" ).innerHTML.replace(/\(.+?\)/,'');
    $( "msg_narrative_trg" ).innerHTML = $( "msg_narrative_trg" ).innerHTML.replace(/\(.+?\)/,'');
  }
  
  // read by search frame
  $('taskNameShort').value = taskNameShort;
}

function loadTopicTD( topicId ) {
  lastTopicId["td"] = topicId;
  if ( topicId=="" ) {
    jQuery('#additional').slideUp("slow",footer);
  } else {
    jQuery('#additional').slideUp("fast", function(){
      var param = eval('$H({"action":"GetTopic", "topicId": "'+topicId+'", "tool": "td"})').toQueryString();
      var json = sync(param);
      loadTopicIntoForm(json);
      loadDynamicAnswerText(json);
      jQuery('#additional').slideDown("slow",footer);

//      var key = taskNameShort+'_'+topicId;
//      var value = getCookie(key);
//      // insert topic into search box
//      top.search.document.getElementById('indriQuery').value = value;
//      //
      
      var qObj = top.search.document.getElementById('querywords');
      if (typeof(qObj) != "undefined") { 
        qObj.value = $('title').value;
      }
    });
  }
}

function addTopic() {
  jQuery('#additional').slideUp("fast", function(){
    var title = $('newTitle').value;
    var param = [];
    param.action = "AddTopic";
    param.title  = es( title );
    param.tool   = "td";
    
    var json = sync(param);
    loadTopicIntoForm(json);
    loadDynamicAnswerText(json);
    
    var t = json.topics[0];
      
    // update topicList 
    var opt = document.createElement("option");
    opt.value = t.topicId;
    opt.id = "topicList"+t.topicId;
    var str = document.createTextNode(t.title);
    opt.appendChild(str);
    $('topicList').appendChild( opt );
    $('topicList').enable();
    $(opt.id).selected = true;
    $('newTitle').value = '';
    showMessage( msg_suc_q_add );
    log("ADD TOPIC",title);
    
    jQuery('#additional').slideDown("slow",footer);
    jQuery('#select_a_task').slideDown("slow",footer);
  });
}

function deleteTopic() {
    // TODO: Cancel from deleting!!!
  if ( !deleteConfirmed() ) return;

  log("DELETE TOPIC",$('title').value);
  var param = [];
  param.action = "DeleteTopic";
  param.topicId  = $('topicId').value;
  param.tool   = "td";
  sync(param);
  var json = eval("({'topics':[{'topicId': -1, 'title': '', 'questionSrc': '', "
      +"'questionTrg': '', 'narrativeSrc': '', 'narrativeTrg': '', 'type': '1', "
      +"'answerText': [], 'note': ''}] })"); //'originalAnswerText': [], 'label': [], 
  loadTopicIntoForm(json);
  loadDynamicAnswerText(json);
  loadTopicList("td"); // TODO: no more hardcode
  $('additional').style.display = 'none';
  showMessage( msg_suc_q_del );
}

function saveTopic() {
  var param = [];
  param.action       = "UpdateTopic";
  param.tool         = "td";
  param.topicId      = $('topicId').value;
  param.externalId   = es( $('externalId').value );
  param.title        = es( $('title').value );
  param.type         = $('type').value;
  param.questionSrc  = es( $('questionSrc').value );
  param.questionTrg  = es( $('questionTrg').value );
  param.narrativeSrc = es( $('narrativeSrc').value );
  param.narrativeTrg = es( $('narrativeTrg').value );
  param.note         = es( $('note').value );
  
  var json = sync(param);
  loadTopicIntoForm(json);
  var prefix = $('externalId').value?($('externalId').value+': '):'';
  $("topicList"+$('topicId').value).innerHTML = prefix+$('title').value;
  log("UPDATE TOPIC",$('title').value);
  showMessage( msg_suc_q_save );
}

//called from loadTopicTD
function loadTopicIntoForm(json) {
  //var i=0;
  var t = json.topics[0];
  $('newTitle').value = '';
  $('topicId').value = t.topicId;
  $('externalId').value = ues( t.externalId );
  $('title').value = ues( t.title );
  $('questionSrc').value = ues( t.questionSrc );
  $('questionTrg').value = ues( t.questionTrg );
  $('narrativeSrc').value = ues( t.narrativeSrc );
  $('narrativeTrg').value = ues( t.narrativeTrg );
  $('note').value = ues( t.note );
  $('questionSrc').innerHTML = ues( t.questionSrc );
  $('questionTrg').innerHTML = ues( t.questionTrg );
  $('narrativeSrc').innerHTML = ues( t.narrativeSrc );
  $('narrativeTrg').innerHTML = ues( t.narrativeTrg );
  $('note').innerHTML = ues( t.note );
  $('done').checked = ( t.done==1 )?true:false;
  
  var type = t.type;
  if ( $('type_'+type)!=null ) {
    $('type_'+type).selected = true;
  } else {
    $('type_').selected = true;
  }
}

function deleteAnswerText(answerId) {
  if ( !deleteConfirmed() ) return;
  var param = [];
  param.action = "DeleteAnswer";
  param.answerId = answerId;
  param.topicId = $('topicId').value;
  param.tool = "td";
  var json = sync(param);
  loadDynamicAnswerText(json);
  log("DELETE ANSWER TEXT","answerId="+answerId);
  showMessage( msg_suc_ans_del );
}

function saveAnswerText(answerId, answerBearingText) {
  if (!answerBearingText) return;
  var param = [];
  param.action = "UpdateAnswerText";
  param.answerId = answerId;
  param.answerBearingText = answerBearingText;
  var json = sync(param);
  $('answerBearingText_'+answerId).innerHTML = answerBearingText;
  log("UPDATE ANSWER TEXT","answerId="+answerId+", answerBearingText="+answerBearingText);
  showMessage( msg_suc_updated );
}

function saveAnswerLabel(answerId, label) {
  if (!label) return;
  var param = [];
  param.action = "UpdateAnswerLabel";
  param.answerId = answerId;
  param.label = label;
  var json = sync(param);
  $('label_'+answerId).innerHTML = label;
  log("UPDATE ANSWER LABEL","answerId="+answerId+", label="+label);
  showMessage( msg_suc_updated );
}

//called by search.js
function addAnswerText() {
  var answer = $('newAnswerText').value;
  var label  = $('newLabel').value;
  
  var param = [];
  param.action = "AddAnswer";
  param.topicId = $('topicId').value;
  param.documentId = $('newDocId').value;
  param.begin = $('begin').value;
  param.end = $('end').value;
  param.answerBearingText = es( answer );
  param.originalAnswerBearingText = es( answer );
  param.label = es( label );
  param.tool = "td";
  log("ADD ANSWER TEXT",(typeof label=="undefined"&&label.length>0?"["+label+"] ":"")+answer);
  if ( $('newDocId').value == "" ) {
    showMessage( msg_warn_docid );
  } else {
    var json = sync(param);
    loadDynamicAnswerText(json);
    showMessage( msg_suc_ans_add ); 
  }
}

function loadDynamicAnswerText(json) {
  var table = '<table width="100%" border="0" cellspacing="0" cellpadding="3">\n'
    + '<tr bgcolor="#00CCFF">\n'
    + '<td><div id="msg_answer_text" align="center" class="bold"></div></td>'
    //+ '<td><div id="msg_doc_id" align="center" class="bold"></div></td>'
    + '<td align="center"></td>'
    + '</tr>\n';
  
  var answers = json.topics[0].answerTexts;
  if (answers) {
    for (var i = 0; i < answers.length; i++) {
      var a = answers[i];
      var id = a.documentId;
      var idlen = id.length;
      if ( idlen > 12 ) {
        id = id.substring(0,12)+"<br>"+id.substring(12,idlen);
      }
  
      var tr = '<tr valign="top" bgcolor="'+((i%2==1)?'#99ffff':'#ccffff')+'">\n'
          + '<td><span class="small">'
          + (a.label.length>0?'[<span id="label_'+a.answerId+'" title="Double-click to edit">'+a.label+'</span>] ':'')
          + '<span id="answerBearingText_'+a.answerId
              +'" title="Double-click to edit.\nOriginal text = '
              +escapeHtml(a.originalAnswerBearingText)+'">'+escapeHtml(a.answerBearingText)+'</span>' 
          + '<span title="begin='+a.begin+', end='+a.end+'"> ('+id+')</span>'
          +'</span></td>\n'
          + '<td align="center"><input class="msg_delete" type="button" '
          + 'style="width:60px" value="DEL" onclick="deleteAnswerText('+a.answerId+')"></td>\n';
          + '</tr>\n';
      table += tr;
    }
  }
  table += "</table>\n";
  $('answerText').innerHTML = table;
  
  jQuery('span[id^="answerBearingText_"]').hover(
    function() {
      jQuery(this).css('border', '1px solid #333333');
    }, 
    function() {
      jQuery(this).css('border', '');
    }
  ).dblclick(function () { 
    var val = prompt("Please edit the ansewr text", this.innerHTML);
    var answerId = this.id.replace(/answerBearingText_/,'');
    saveAnswerText(answerId, val);
  }).tipsy({gravity: 'n'});
  jQuery('span[id^="label_"]').hover(
      function() {
        jQuery(this).css('border', '1px solid #333333');
      }, 
      function() {
        jQuery(this).css('border', '');
      }
  ).dblclick(function () { 
    var val = prompt("Please edit the label", this.innerHTML);
    var answerId = this.id.replace(/label_/,'');
    saveAnswerLabel(answerId, val);
  }).tipsy({gravity: 'w'});
  
  //loading messages...
  loadMessages(lang);
}

function loadTypes( types ) {
  for ( var i=0; i<types.length; i++ ) {
    var opt = document.createElement("option");
    opt.id = "type_"+types[i];
    opt.value = types[i];
    opt.innerHTML = types[i];
    $('type').appendChild(opt);
  }
  var opt = document.createElement("option");
  opt.id = "type_";
  opt.value = "";
  opt.innerHTML = " ";
  opt.selected = true;
  $('type').appendChild(opt);
}

function scrollDown() {
  jQuery('html,body').animate({scrollTop: jQuery('body').height()}, 'fast');
}

function escapeHtml(htmlString) {
  return htmlString
  .replace(/&/g, "&amp;")
  .replace(/</g, "&lt;")
  .replace(/>/g, "&gt;")
  .replace(/"/g, "&quot;")
  .replace(/'/g, "&apos;");
}
